package com.hptpd.questionnairesurvey.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hptpd.questionnairesurvey.component.Result;
import com.hptpd.questionnairesurvey.domain.Department;
import com.hptpd.questionnairesurvey.domain.Survey;
import com.hptpd.questionnairesurvey.domain.UserSurvey;
import com.hptpd.questionnairesurvey.domain.UserSurveyScore;
import com.hptpd.questionnairesurvey.repository.SurveyRep;
import com.hptpd.questionnairesurvey.repository.UserSurveyRep;
import com.hptpd.questionnairesurvey.service.IStatisticService;
import com.hptpd.questionnairesurvey.vo.DepartmentVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * \* Created with IntelliJ IDEA.
 * \* Date: 2019/12/26
 * \*
 * \* Description:
 * \
 *
 * @author walter_long
 */
@Service("iStatisticService")
public class StatisticServiceImpl implements IStatisticService {
    @Resource
    private SurveyRep surveyRep;
    @Resource
    private UserSurveyRep userSurveyRep;

    @Override
    public Result getSurveyFeedbackByRootDepartment(@NotNull String surveyId) {
        Survey survey = surveyRep.getOne(surveyId);
        Map<String, Object> dest = Maps.newLinkedHashMap();
        Map<Department, Integer> sumMap = Maps.newHashMap();
        Map<Department, Integer> doneMap = Maps.newHashMap();
        List<Map<String, Object>> dataList = Lists.newLinkedList();
        if (null != survey) {
            List<UserSurvey> userSurveyList = survey.getUserSurveys();
            for (UserSurvey userSurvey : userSurveyList) {
                Department root = DepartmentVo.getRootDepartment(userSurvey.getUser().getDepartment());
                if (!sumMap.containsKey(root)) {
                    sumMap.put(root, 1);
                } else {
                    sumMap.replace(root, sumMap.get(root) + 1);
                }
                if (userSurvey.getIsDone()) {
                    if (!doneMap.containsKey(root)) {
                        doneMap.put(root, 1);
                    } else {
                        doneMap.replace(root, doneMap.get(root) + 1);
                    }
                }
            }
            sumMap.keySet().forEach(v -> {
                Map<String, Object> map = Maps.newLinkedHashMap();
                map.put("name", v.getName());
                map.put("doneRate", new BigDecimal(null == doneMap.get(v) ? 0 : doneMap.get(v)).divide(new BigDecimal(sumMap.get(v)), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).toString() + "%");
                map.put("doneSum", null == doneMap.get(v) ? 0 : doneMap.get(v));
                map.put("sum", sumMap.get(v));
                dataList.add(map);
            });
            dest.put("tableData", dataList);

            List<Map<String, String>> headList = getHeadList("name", "单位", "doneSum", "反馈人数", "sum", "推送人数", "doneRate", "问卷填报率");
            dest.put("headData", headList);

            return Result.ok(dest);
        }
        return Result.badArgumentValue();
    }

    @Override
    public Result getSurveyAvgScoreByRootDepartment(@NotNull String surveyId) {
        List<UserSurvey> userSurveys = userSurveyRep.findByIsDoneAndSurvey_Id(true, surveyId);
        if (null == userSurveys) {
            return Result.badArgumentValue();
        } else if (userSurveys.isEmpty()) {
            return Result.fail(-1, "没有人完成调查");
        }
        Map<String, Object> dest = Maps.newLinkedHashMap();
        List<Map<String, Object>> dataList = Lists.newLinkedList();

        Map<Department, Integer> peopleCountMap = Maps.newHashMap();
        Map<Department, BigDecimal> scoreSumMap = Maps.newHashMap();

        for (UserSurvey userSurvey : userSurveys) {
            Department root = DepartmentVo.getRootDepartment(userSurvey.getUser().getDepartment());
            List<UserSurveyScore> userSurveyScores = userSurvey.getUserSurveyScores();
            BigDecimal bigDecimal = new BigDecimal(0);
            for (UserSurveyScore userSurveyScore : userSurveyScores) {
                bigDecimal = bigDecimal.add(userSurveyScore.getHundredMarkScore());
            }
            if (!scoreSumMap.containsKey(root)) {
                scoreSumMap.put(root, bigDecimal);
                peopleCountMap.put(root, 1);
            } else {
                scoreSumMap.replace(root, scoreSumMap.get(root).add(bigDecimal));
                peopleCountMap.replace(root, peopleCountMap.get(root) + 1);
            }
        }
        scoreSumMap.keySet().forEach(v -> {
            Map<String, Object> map = Maps.newLinkedHashMap();
            map.put("name", v.getName());
            map.put("avgScore", scoreSumMap.get(v).divide(new BigDecimal(peopleCountMap.get(v)), 1, BigDecimal.ROUND_HALF_UP));
            dataList.add(map);
        });

        dataList.sort(Comparator.comparing(o -> ((BigDecimal) o.get("avgScore"))));

        int i = 1;
        for (Map<String, Object> map : dataList) {
            map.put("top", i++);
        }

        dest.put("tableData", dataList);

        List<Map<String, String>> headList = getHeadList("name", "单位", "avgScore", "均分", "top", "排名");
        dest.put("headData", headList);

        return Result.ok(dest);
    }

    @Override
    public Result getSurveyDimensionalityScoreByRootDepartment(String surveyId) {
        List<UserSurvey> userSurveys = userSurveyRep.findByIsDoneAndSurvey_Id(true, surveyId);
        if (null == userSurveys) {
            return Result.badArgumentValue();
        } else if (userSurveys.isEmpty()) {
            return Result.fail(-1, "没有人完成调查");
        }

        Map<String, Object> dest = Maps.newLinkedHashMap();
        List<Map<String, Object>> dataList = Lists.newLinkedList();

        for (UserSurvey userSurvey : userSurveys) {
            List<UserSurveyScore> userSurveyScores = userSurvey.getUserSurveyScores();
            for (UserSurveyScore userSurveyScore : userSurveyScores) {
                userSurveyScore.getDimensionality();
                Department root = DepartmentVo.getRootDepartment(userSurvey.getUser().getDepartment());
            }
        }

        dest.put("tableData", dataList);

        List<Map<String, String>> headList = getHeadList("name", "单位", "avgScore", "均分", "top", "排名");
        dest.put("headData", headList);

        return null;
    }

    private Result validateUserSurveys(List<UserSurvey> userSurveys) {
//       if (null == userSurveys) {
//           return Result.badArgumentValue();
//       } else if (userSurveys.isEmpty()) {
//           return Result.fail(-1, "没有人完成调查");
//       }
       return null;
    }

    private List<Map<String, String>> getHeadList(String ...strArr) {
        int mod = 2;
        if (null == strArr || strArr.length % mod != 0) {
            return null;
        }
        List<Map<String, String>> dest = Lists.newLinkedList();
        for (int i = 0; i < strArr.length; i++) {
            Map<String, String> map = Maps.newLinkedHashMap();
            map.put("key", strArr[i]);
            map.put("label", strArr[++i]);
            dest.add(map);
        }
        return dest;
    }
}
